<template>
  <!-- 弹窗遮罩层，v-if 配合 visible 控制显示 -->
  <div class="address-modal-overlay" v-if="visible" @click="handleOverlayClick">
    <!-- 弹窗内容容器，阻止遮罩层点击事件穿透 -->
    <div class="address-modal" @click.stop>
      <div class="modal-header">
        <h3>{{ isEditing ? '编辑收货人信息' : '新增收货人信息' }}</h3>
        <!-- 关闭按钮 -->
        <span class="close-btn" @click="handleClose">×</span>
      </div>
      <div class="modal-body">
        <!-- 表单内容 -->
        <div class="form-group">
          <label class="required">所在地区</label>
          <select v-model="form.region">
            <option value="">--请选择--</option>
            <option value="河北省">河北省</option>
            <option value="北京市">北京市</option>
            <!-- 更多地区选项 -->
          </select>
        </div>
        <div class="form-group">
          <label class="required">收货人</label>
          <input type="text" v-model="form.receiver" placeholder="请输入收货人姓名">
        </div>
        <div class="form-group">
          <label class="required">详细地址</label>
          <input type="text" v-model="form.detailAddress" placeholder="请输入详细地址">
        </div>
        <div class="form-group">
          <label class="required">手机号码</label>
          <div class="phone-input">
            <span class="country-code">0086</span>
            <input type="tel" v-model="form.phone" placeholder="请输入手机号码">
          </div>
        </div>
        <div class="form-group">
          <label>固定电话</label>
          <div class="phone-input">
            <span class="country-code">0086</span>
            <input type="tel" v-model="form.fixedPhone" placeholder="选填">
          </div>
        </div>
        <div class="form-group">
          <label>邮箱地址</label>
          <input type="email" v-model="form.email" placeholder="选填，接收订单提醒">
        </div>
        <div class="form-group">
          <label>地址别名</label>
          <input type="text" v-model="form.alias" placeholder="选填（如家里、公司等）">
        </div>

        <!-- 只有在编辑或有多个地址时显示设为默认选项 -->
        <div class="form-group" v-if="isEditing || addressStore.addresses.length > 0">
          <label></label>
          <label class="checkbox-label">
            <input
              type="checkbox"
              v-model="setAsDefault"
              :checked="isEditing && form.id === addressStore.defaultAddressId"
            >
            设为默认收货地址
          </label>
        </div>
      </div>
      <div class="modal-footer">
        <button class="save-btn" @click="handleSave">保存收货人信息</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue';
import { useAddressStore } from '@/stores/address_info';

// 引入地址存储
const addressStore = useAddressStore();

// 接收父组件传递的参数
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  // 用于编辑已有地址
  addressId: {
    type: String,
    default: null
  }
});

// 定义触发的事件
const emit = defineEmits(['close']);

// 表单数据
const form = ref({
  id: '',
  region: '',
  receiver: '',
  detailAddress: '',
  phone: '',
  fixedPhone: '',
  email: '',
  alias: ''
});

// 是否设为默认地址
const setAsDefault = ref(false);

// 是否处于编辑状态
const isEditing = ref(!!props.addressId);

// 先定义resetForm函数，确保在watch中可以访问
const resetForm = () => {
  form.value = {
    id: '',
    region: '',
    receiver: '',
    detailAddress: '',
    phone: '',
    fixedPhone: '',
    email: '',
    alias: ''
  };
  setAsDefault.value = false;
  isEditing.value = false;
};

// 只保留一个watch监听器
watch(() => props.addressId, (newId) => {
  if (newId) {
    isEditing.value = true;
    const address = addressStore.getAddressById(newId);
    if (address) {
      form.value = { ...address };
      // 检查是否是默认地址
      setAsDefault.value = address.id === addressStore.defaultAddressId;
    }
  } else {
    // 现在resetForm已经定义，可以安全调用
    resetForm();
  }
}, { immediate: true });

// 初始化地址存储
addressStore.init();

// 关闭弹窗
const handleClose = () => {
  emit('close');
  resetForm();
};

// 点击遮罩层关闭弹窗
const handleOverlayClick = () => {
  handleClose();
};

// 保存地址逻辑
const handleSave = () => {
  // 表单验证
  if (!form.value.region) {
    alert('请选择所在地区');
    return;
  }
  if (!form.value.receiver) {
    alert('请输入收货人姓名');
    return;
  }
  if (!form.value.detailAddress) {
    alert('请输入详细地址');
    return;
  }
  if (!form.value.phone) {
    alert('请输入手机号码');
    return;
  }

  // 保存地址
  const addressId = addressStore.saveAddress(form.value);

  // 如果需要设为默认地址
  if (setAsDefault.value || addressStore.addresses.length === 1) {
    addressStore.setDefaultAddress(addressId);
  }

  alert(isEditing.value ? '地址更新成功！' : '地址添加成功！');
  handleClose();
};
</script>


<style scoped lang="scss">
/* 弹窗遮罩层样式 */
.address-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

/* 弹窗容器样式 */
.address-modal {
  width: 700px;
  height: auto; /* 改为自动高度适应内容 */
  min-height: 500px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 弹窗头部 */
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #e0e0e0;
  background-color: #f8f8f8;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
  }

  .close-btn {
    font-size: 20px;
    cursor: pointer;
    color: #999;
    transition: color 0.2s;

    &:hover {
      color: #333;
    }
  }
}

/* 弹窗主体内容 */
.modal-body {
  padding: 20px;

  .form-group {
    margin-bottom: 14px;
    display: flex; /* 使用flex布局让标签和输入框在同一行 */
    align-items: center; /* 垂直居中对齐 */

    label {
      display: inline-block;
      width: 80px;
      text-align: right;
      margin-right: 10px;
      color: #333;
      line-height: 30px;
    }

    .required::after {
      content: '*';
      color: red;
      margin-left: 2px;
    }

    input,
    select {
      width: 300px;
      padding: 3px 5px;
      height: 28px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
      box-sizing: border-box;
      text-align: left; /* 确保输入内容左对齐 */

      &:focus {
        outline: none;
        border-color: #4d90fe;
        box-shadow: 0 0 0 2px rgba(77, 144, 254, 0.2);
      }
    }

    .phone-input {
      display: flex;
      align-items: center;
      width: 300px; /* 与其他输入框保持相同宽度 */

      .country-code {
        padding: 0 5px;
        height: 28px;
        line-height: 28px;
        border: 1px solid #ddd;
        border-right: none;
        border-radius: 4px 0 0 4px;
        background-color: #f5f5f5;
        box-sizing: border-box;
        font-size: 14px;
      }

      input {
        border-radius: 0 4px 4px 0;
        margin-left: -1px;
        width: calc(100% - 40px); /* 计算输入框宽度，确保整体宽度一致 */
      }
    }
  }
}

/* 弹窗底部按钮 */
.modal-footer {
  padding: 12px 20px;
  background-color: #f8f8f8;

  .save-btn {
    padding: 5px 13px;
    height: 30px;
    line-height: 25px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;
    box-sizing: border-box;
  }

  .save-btn {
    background-color: #e53e3e;
    color: #fff;

    &:hover {
      background-color: #c53030;
    }
  }
}
</style>
